package io.hellsinger.vortex.ui.screen.settings

import android.content.Context
import android.os.Bundle
import android.view.View
import io.hellsinger.navigation.screen.HostScreenController
import io.hellsinger.navigation.screen.ScreenController
import io.hellsinger.theme.vortex.VortexSettings
import io.hellsinger.vortex.navigation.globalUiProvider
import io.hellsinger.vortex.ui.component.drawable.RoundedCornerDrawable
import io.hellsinger.vortex.ui.screen.settings.color.ColorSettingsOptionsRenderer
import io.hellsinger.vortex.ui.screen.settings.text.TextSettingsOptionsRenderer

class SettingsScreenController(
    private val context: Context,
) : HostScreenController<Unit>() {
    private val bar = globalUiProvider(context)?.bar

    override fun getControllerCount(): Int = SCREEN_COUNT

    override fun onCreateViewImpl(context: Context): View =
        super.onCreateViewImpl(context).apply {
            background =
                RoundedCornerDrawable(VortexSettings.colors { key_storage_list_background_color })
        }

    override fun createScreenController(position: Int): ScreenController<*> =
        when (position) {
            SCREEN_COLOR -> SettingsEntryScreenController(context, ColorSettingsOptionsRenderer())
            SCREEN_TEXT -> SettingsEntryScreenController(context, TextSettingsOptionsRenderer())

            else -> throw IllegalArgumentException("Illegal position for SettingsScreenController")
        }

    override fun onPrepareImpl() {
        bar?.replaceItems(emptyList())
        bar?.title =
            when (pager?.currentItem ?: return) {
                SCREEN_COLOR -> "Colors"
                SCREEN_TEXT -> "Texts"
                else -> throw IllegalArgumentException("Illegal position for SettingsScreenController")
            }
    }

    override fun onBackActivatedImpl(): Boolean = false

    override fun onFocusImpl() {
    }

    override fun onHideImpl() {
    }

    override fun onSaveImpl(
        buffer: Bundle,
        prefix: String,
    ): Boolean = false

    override fun onRestoreImpl(
        buffer: Bundle,
        prefix: String,
    ): Boolean = false

    override fun onDestroyImpl() {
        adapter.destroy()
        pager?.removeAllViews()
        pager = null
    }

    companion object {
        const val SCREEN_COUNT = 2

        const val SCREEN_COLOR = 0
        const val SCREEN_TEXT = 1
    }
}
